#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	STDataType* temp = (STDataType*)malloc(sizeof(STDataType) * 4);
	if (temp == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ps->a = temp;
	ps->top = 0;
	ps->capacity = 4;
}
void StackCheckCapacity(Stack* ps)
{
	assert(ps);
	// 扩容
	if (ps->top == ps->capacity)
	{
		STDataType* temp = (STDataType*)realloc(ps->a, sizeof(STDataType) * 2 * ps->capacity);
		if (temp == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->a = temp;
		ps->capacity = 2 * ps->capacity;
	}
}

bool StackEmpty(Stack* ps)
{
	assert(ps);
	// 空时返回true，不为空返回false
	return ps->top == 0;
}


void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	StackCheckCapacity(ps);
	ps->a[ps->top] = data;
	ps->top++;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->a[ps->top - 1];
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}
